<template>
  <div class="alarmConfiguration zy-content">
    <search :columns="searchData" @getSearch="getSearch(arguments)"></search>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="exportTemplateClick">{{ $t('common.Export') }}</Button>
        <Button @click="branchPushOfTime">范围批量推送</Button>
        <Button @click="branchPush">数据批量推送</Button>
        <Button @click="getTableColumns(columns)">
          {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
        </Button>
      </div>
      <!-- 表格 -->
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            :columns="columnsList"
            ellipsis
            ref="selection"
            stripe
            @on-selection-change="onSelectChange"
            :data="dataArr"
        >
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="handleClick1(row)">数据重推</span>
          </template>
        </Table>
      </div>
      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="delIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <!-- 请确认是否删除弹框 -->
    <Modal :mask-closable="false" v-model="delFaultCodeShowF" title="数据重推" class="modal-title-layout">
      <p class="title">是否重新推送该业务</p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">
          {{ $t('common.Cancle') }}
        </Button>
        <Button type="primary" :loading="loading" @click="deleteOK">
          {{ $t('maintenance.Confirmed') }}
        </Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" class="modal-title-layout" v-model="branchPushOfTimeShowF" title="重推范围选择">
      <Form ref="form" :model="benchPushForm" label-position="top">
        <FormItem label="时间范围" prop="timeRange">
          <DatePicker :value="timeRange" type="datetimerange" @on-change="(val) => (timeRange = val)"
                      format="yyyy-MM-dd HH:mm:ss"></DatePicker>
        </FormItem>
        <FormItem label="处理业务" prop="handleBusiness">
          <Select v-model="handleBusiness" clearable>
            <Option v-for="(item, index) of bussessList" :value="item.str" :key="index" :label="item.str"></Option>
          </Select>
          <!-- <DatePicker :value="handleBusiness" type="datetimerange" @on-change="(val) => (handleBusiness = val)" format="yyyy-MM-dd HH:mm:ss"></DatePicker> -->
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="branchPushOfTimeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="repairLoading" @click="confirmBenchPush()">{{
            $t('maintenance.Confirmed')
          }}
        </Button>
      </div>
    </Modal>
    <commonModal ref="commonModal"></commonModal>
  </div>
</template>

<script>
import search from '@/components/curd/searchList.vue';
import fileDownload from 'js-file-download';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import commonModal from '@/components/modalTypes/commonModal.vue';

export default {
  name: 'logPush',
  components: {search, commonModal},
  mixins: [toggleTableOperation],
  data() {
    return {
      timeRange: '',
      handleBusiness: '',
      loading: false,
      create: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchData: [
        {
          title: '处理结果',
          key: 'handleResult',
          type: 'select',
          dicData: [
            {
              label: '成功',
              value: '成功',
            },
            {
              label: '失败',
              value: '失败',
            },
          ],
        },
        {
          title: '处理业务',
          key: 'handleBusiness',
          type: 'select',
          dicUrl: '/dms/thirdPartyLog/handle/business',
          params: {
            label: 'str',
            value: 'str',
          },
        },
        {
          title: '请求参数',
          key: 'handleParam',
        },
        {
          title: '响应内容',
          key: 'responseResult',
        },
        {
          title: '数据流向',
          key: 'flowTo',
          type: 'select',
          dicData: [
            {
              label: 'MES->WMS',
              value: 'MES->WMS',
            },
            {
              label: 'MES->SAP',
              value: 'MES->SAP',
            },
          ],
        },
        {
          title: '创建人',
          key: 'createName',
        },
        {
          title: '修改人',
          key: 'updateName',
        },
        {
          title: '创建时间',
          key: 'time',
          type: 'daterange',
          defaultTimeRange: 7,
          noreset: true,
          clearable: false,
        },
        {
          title: '修改时间',
          key: 'time2',
          type: 'daterange',
        },
      ],
      columns: [
        {
          key: 'selection',
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center',
          render: (h, params) => {
            return h('div', params.row._index + (this.pageNum - 1) * this.pageSize + 1);
          },
        },
        {
          title: '处理业务',
          key: 'handleBusiness',
          minWidth: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },

        {
          title: '处理地址',
          key: 'handleUrl',
          minWidth: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '请求参数',
          key: 'handleParam',
          width: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '响应结果',
          key: 'handleResult',
          minWidth: 150,
          align: 'center',
          resizable: true,
        },
        {
          title: '响应内容',
          key: 'responseResult',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '是否报错',
          key: 'isSysError',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '报错信息',
          key: 'errorMsg',
          minWidth: 150,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '数据流向',
          key: 'flowTo',
          minWidth: 130,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '创建人',
          key: 'createName',
          minWidth: 150,
          align: 'center',
          resizable: true,
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth: 150,
          align: 'center',
          resizable: true,
        },
        {
          title: '修改人',
          key: 'updateName',
          minWidth: 150,
          align: 'center',
          resizable: true,
        },
        {
          title: '修改时间',
          key: 'updateTime',
          minWidth: 150,
          align: 'center',
          resizable: true,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          fixed: 'right',
          minWidth: 160,
          align: 'center',
        },
      ],
      dataArr: [],
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      selection: [],
      delFaultCodeShowF: false,
      branchPushOfTimeShowF: false,
      currentRow: {},
      bussessList: [],
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.axios({
      url: '/dms/thirdPartyLog/handle/business',
      method: 'get',
    }).then((res) => {
      if (res.code === 200) {
        this.bussessList = res.data;
      }
    });
    const today = new Date();
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(today.getDate() - 7);
    this.searchParams = {
      creatEndTime: this.getFormattedDate(sevenDaysAgo),
      creatStartTime: this.getFormattedDate(today)
    }
    this.searchList();

  },
  methods: {
    getFormattedDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getSearch(arg) {
      this.searchParams = JSON.parse(JSON.stringify(arg[0]));
      const {time, time2} = this.searchParams;
      if (time && time.length == 2) {
        this.searchParams.creatStartTime = time[0];
        this.searchParams.creatEndTime = time[1];
        delete this.searchParams.time;
      }
      if (time2 && time2.length == 2) {
        this.searchParams.updateStartTime = time2[0];
        this.searchParams.updateEndTime = time2[1];
        delete this.searchParams.time2;
      }
      this.pageNum = 1;
      this.searchList();
    },
    branchPushOfTime() {
      this.branchPushOfTimeShowF = true;
    },
    confirmBenchPush() {
      let resBoolarn = (this.timeRange && this.timeRange.length > 0) || this.handleBusiness;
      if (resBoolarn) {
        this.repairLoading = true;
        this.axios({
          url: '/dms/thirdPartyLog/rePushByTime',
          method: 'put',
          data: {
            startDateTime: this.timeRange[0],
            endDateTime: this.timeRange[1],
            handleBusiness: this.handleBusiness
          },
        }).then((res) => {
          this.repairLoading = false;
          if (res.code === 200) {
            this.branchPushOfTimeShowF = false;
            this.searchList();
            this.$Message.success({
              content: res.data || res.msg,
              duration: 6,
              closable: true,
            });
          } else {
            this.searchList();
            this.$Message.warning({
              content: res.data || res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      } else {
        this.$Message.warning('请选择时间范围或处理业务');
      }
    },
    branchPush() {
      if (this.delIds.length == 0) {
        this.$Message.warning('至少选择一条数据');
        return;
      }
      this.$refs.commonModal.showModal({
        title: '批量数据重推',
        type: 'sure',
        desc: '是否批量重新推送业务',
        submit: () => {
          this.axios({
            url: '/dms/thirdPartyLog/rePush',
            method: 'put',
            data: this.delIds,
          }).then((res) => {
            if (res.code === 200) {
              this.delFaultCodeShowF = false;
              this.searchList();
              this.$Message.success({
                content: res.data || '操作成功',
                duration: 6,
                closable: true,
              });
            } else {
              this.searchList();
              this.$Message.warning({
                content: res.data,
                duration: 6,
                closable: true,
              });
            }
          });
        },
      });
    },
    handleClick1(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.currentRow = row;
    },
    deleteOK() {
      this.delFaultCodeShowF = false;
      this.axios({
        url: '/dms/thirdPartyLog/rePush',
        method: 'put',
        data: [this.currentRow.id],
      }).then((res) => {
        if (res.code === 200) {
          this.delFaultCodeShowF = false;
          this.$Message.success({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
      };
      this.axios({
        method: 'post',
        url: '/dms/thirdPartyLog/page',
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    //导出
    exportTemplateClick() {
      let params = {
        ...this.searchParams,
      };
      if (params.creatStartTime == null || params.creatStartTime == null) {
        this.$Message.warning('请选择创建时间或者修改时间');
        return;
      }
      const filName = '推送日志记录';
      this.axios({
        method: 'post',
        url: '/dms/thirdPartyLog/export',
        data: params,
      }).then((res) => {
        if (res.code == 555) {
          this.$Message.warning(res.msg);
        } else {
          this.axios({
            method: 'post',
            url: '/dms/thirdPartyLog/export',
            responseType: 'blob',
            data: params,
          }).then((res) => {
            fileDownload(res, filName + '.xlsx');
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}

.row_click {
  cursor: pointer;
  color: rgb(50, 113, 240) !important;
}
</style>
